package com.forever7776.life.web.controller.life.front;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.forever7776.life.core.common.vo.*;
import com.forever7776.life.core.entity.blog.Blog;
import com.forever7776.life.core.entity.blog.BlogExt;
import com.forever7776.life.core.entity.blog.BlogType;
import com.forever7776.life.core.entity.comment.CommentBlog;
import com.forever7776.life.core.entity.stat.StatBlog;
import com.forever7776.life.core.entity.sys.SysUser;
import com.forever7776.life.core.service.blog.IBlogExtService;
import com.forever7776.life.core.service.blog.IBlogService;
import com.forever7776.life.core.service.blog.IBlogTypeService;
import com.forever7776.life.core.service.collect.ICollectBlogService;
import com.forever7776.life.core.service.comment.ICommentBlogService;
import com.forever7776.life.core.service.praise.IPraiseDetailBlogService;
import com.forever7776.life.core.service.stat.IStatBlogService;
import com.forever7776.life.core.service.sys.ISysUserService;
import com.forever7776.life.remote.common.enums.StatusEnum;
import com.forever7776.life.remote.common.vo.ResultVO;
import com.forever7776.life.web.controller.BaseController;
import enums.ResultEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import util.ResultUtil;

import java.util.LinkedList;
import java.util.List;


/**
 * 博客
 *
 * @author kz
 * @date 2018年02月10日
 */
@Controller
@RequestMapping(value = "/blog")
public class FrontBlogController extends BaseController {

    @Autowired
    private IBlogService iBlogService;
    @Autowired
    private IBlogExtService iBlogExtService;
    @Autowired
    private IBlogTypeService iBlogTypeService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IStatBlogService iStatBlogService;
    @Autowired
    private ICommentBlogService iCommentBlogService;
    @Autowired
    private IPraiseDetailBlogService iPraiseDetailBlogService;
    @Autowired
    private ICollectBlogService iCollectBlogService;

    @RequestMapping
    public String index(ModelMap map) {
        map.put("type", 0);
        map.put("types", iBlogTypeService.selectAll(StatusEnum.NORMAL.getKey()));
        map.put("blogActiveUsers", iBlogService.selectBlogActiveUser(pageSize));
        return FRONT_VIEW_PAGE_PATH_LIFE + "front/blog";
    }

    /**
     * 查询用户发布的博客
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject list(@RequestParam(value = "type", defaultValue = "0") Integer type,
                           @RequestParam(value = "blogTypeId", required = false) Integer blogTypeId) {
        JSONObject result = new JSONObject();
        Page<UserBlogVO> p = new Page<UserBlogVO>();
        p.setCurrent(pageNumber);
        Page<UserBlogVO> page = iBlogService.selectAllUserBlogByFront(p, type, blogTypeId, null);
        result.put("type", type);
        result.put("page", page);
        return result;
    }

    /**
     * 查看博客
     *
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    public String view(@PathVariable Integer id, ModelMap modelMap) {
        Blog blog = iBlogService.selectById(id);

        String userId = blog.getUserId();
        BlogExt blogExt = iBlogExtService.selectByBlogId(id);
        SysUser user = iSysUserService.selectById(userId);

        List<BlogType> list = iBlogTypeService.selectAll(StatusEnum.NORMAL.getKey());
        UserLastBlogVO lastBlog = iBlogService.selectUserLastBlog(userId, id);
        SysUser currentUser = getSysUser();
        if (currentUser != null) {
            modelMap.put("praiseDetail", iPraiseDetailBlogService.selectPraiseOneByUserIdAndBlogId(currentUser.getId(), id));
            modelMap.put("collectDetail", iCollectBlogService.selectCollectOneByUserIdAndBlogId(currentUser.getId(), id));
        }

        modelMap.put("id", id);
        modelMap.put("user", user);
        modelMap.put("blogTypes", iBlogTypeService.createBlogTypeMap(list));
        modelMap.put("blogCount", iBlogService.selectCount(userId));
        modelMap.put("blog", blog);
        modelMap.put("lastBlog", lastBlog);
        modelMap.put("blogExt", blogExt);
        return FRONT_VIEW_PAGE_PATH_LIFES + "front/blog";
    }

    /**
     * 查询该博客统计数据
     *
     * @param id
     */
    @RequestMapping(value = "/stat/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectStatByBlogId(@PathVariable Integer id) {
        JSONObject result = new JSONObject();
        List<Integer> thirdIds = new LinkedList<>();
        thirdIds.add(id);
        List<StatBlog> stat = iStatBlogService.selectByBlogIds(thirdIds);
        result.put("stat", CollectionUtils.isNotEmpty(stat) ? stat.get(0) : null);
        result.put("code", 0);
        return result;
    }

    /**
     * 查询博客评论列表
     *
     * @param id
     * @return
     */
    @RequestMapping("/comments/{id}")
    @ResponseBody
    public JSONObject blogComments(@PathVariable Integer id) {
        JSONObject result = new JSONObject();
        Blog blog = iBlogService.selectById(id);
        String userId = blog.getUserId();
        Page<UserCommentVO> p = new Page<>();
        p.setCurrent(pageNumber);
        Page<UserCommentVO> page = iCommentBlogService.selectBlogCommentsList(p, id, userId);
        List<String> userIds = iCommentBlogService.selectBlogCommentUserIds(id);
        List<UserBaseInfoVO> users = iSysUserService.selectUserBaseInfos(userIds);
        result.put("usersMap", createUserMap(users));
        result.put("page", page);
        return result;
    }


    /**
     * 查看博客,查询5条热文博客
     *
     * @return
     */
    @RequestMapping("/hot")
    @ResponseBody
    public JSONObject hot(@RequestParam("blogId") Integer blogId) {
        JSONObject result = new JSONObject();
        List<UserBlogBaseVO> list = iBlogService.selectFiveHotBlog(blogId);
        result.put("list", list);
        result.put("code", ResultEnum.STATUS.SUCCESS.getCode());
        return result;
    }

    /**
     * 查询最新博客
     *
     * @return
     */
    @RequestMapping("/type/{type}")
    @ResponseBody
    public JSONObject newestBlog(@PathVariable Integer type, @RequestParam("id") Integer id) {
        JSONObject result = new JSONObject();
        List<UserBlogVO> list = iBlogService.selectUserBlogByCondition(id, type, null);
        result.put("list", list);
        return result;
    }

    /**
     * 博客详情页面，添加评论
     *
     * @param blogId
     * @param content
     * @return
     */
    @RequestMapping(value = "/add/comment/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addComment(@PathVariable Integer blogId,
                                 @RequestParam("content") String content,
                                 @RequestParam(value = "replyId", required = false) String replyId) {
        if (blogId == null || blogId < 1) {
            return ResultUtil.getFailResult("该博客不存在~");
        }
        if (StringUtils.isEmpty(content) || content.length() > 255) {
            return ResultUtil.getFailResult("内容不规范~");
        }
        CommentBlog comment = new CommentBlog();
        comment.setBlogId(blogId);
        comment.setUserId(getUserId());
        comment.setContent(content);
        comment.setReplyUserId(replyId);
        iCommentBlogService.insert(comment);
        return ResultUtil.getSuccessResult("评论成功~");
    }

    /**
     * 添加博客阅读数量
     *
     * @param blogId
     */
    @RequestMapping(value = "/add/read/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO addRead(@PathVariable Integer blogId) {
        logger.info("博客阅读,userId={},blogId={}", blogId);
        return iStatBlogService.addReadStat(blogId);
    }

    /**
     * 给博客点赞
     *
     * @param blogId
     */
    @RequestMapping(value = "/add/praise/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO addPraise(@PathVariable Integer blogId) {
        String userId = getUserId();
        logger.info("博客点赞,userId={},blogId={}", userId, blogId);
        return iStatBlogService.addPraiseStat(userId, blogId);
    }

    /**
     * 给博客取消点赞
     *
     * @param blogId
     */
    @RequestMapping(value = "/cut/praise/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO cutPraise(@PathVariable Integer blogId) {
        String userId = getUserId();
        logger.info("博客取消点赞,userId={},blogId={}", userId, blogId);
        return iStatBlogService.cutPraiseStat(userId, blogId);
    }

    /**
     * 收藏博客
     *
     * @param blogId
     */
    @RequestMapping(value = "/add/collect/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO addCollect(@PathVariable Integer blogId) {
        String userId = getUserId();
        logger.info("收藏博客,userId={},blogId={}", userId, blogId);
        return iCollectBlogService.addCollectStat(userId, blogId);
    }

    /**
     * 取消收藏博客
     *
     * @param blogId
     */
    @RequestMapping(value = "/cut/collect/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO cutCollect(@PathVariable Integer blogId) {
        String userId = getUserId();
        logger.info("取消收藏博客,userId={},blogId={}", userId, blogId);
        return iCollectBlogService.cutCollectStat(userId, blogId);
    }

}
